const Model = require('./index')

class CommentModel extends Model {
  /**
   * 分页查询评论列表
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} conditions
   * @returns
   */
  async findPage ({ pageNo, pageSize, conditions }) {
    const conditionSql = this.generateWhereClauseOR(conditions)
    const sql = `select comment.*, (select count(*) from user_agree_comment uac where comment.id = uac.commentId) as likeCounts,
      user.nickname${this.tableName === 'article_comment' ? ', article.articleTitle' : ', sc.content as circleContent, sc.picList'} 
      from ${this.tableName} comment
      left join user on user.id = comment.userId 
      ${this.tableName === 'article_comment' ? 'left join article on article.id = comment.articleId' : 'left join share_circle sc on sc.id = comment.circleId'} ${conditionSql} 
      order by comment.userId desc, comment.createTime desc
      limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(conditionSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  async total (conditionSql) {
    const sql = `select count(*) as total from ${this.tableName} comment left join user on user.id = comment.userId ${conditionSql}`
    try {
      const total = await this.db.query(sql)
      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  async delete (id) {
    const sql = `delete ${this.tableName}, uac from ${this.tableName} 
      left join user_agree_comment uac on uac.commentId = ${this.tableName}.id
      where id = ? or topId = ?`
    try {
      await this.db.query(sql, [id, id])
    } catch (error) {
      throw new Error(error)
    }
  }
}

exports.articleCommentModel = new CommentModel('article_comment')
exports.circleCommentModel = new CommentModel('sharecircle_comment')
